const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');

const app = express();
const PORT = 8080;

// 安全中间件 - 限制访问路径
const securityMiddleware = (req, res, next) => {
  const allowedPaths = [
    '/',
    '/index.html',
    '/submit.html',
    '/css/',
    '/js/',
    '/images/',
    '/favicon.ico',
    '/admin/'
  ];
  
  const allowedApiPaths = [
    '/api/regions',
    '/api/clue-categories', 
    '/api/clues',
    '/api/clues/query',
    '/api/submit-clue',
    '/api/send-sms',
    '/api/verify-sms'
  ];
  
  // 检查是否为允许的静态文件路径
  const isAllowedStatic = allowedPaths.some(path => 
    req.path === path || req.path.startsWith(path)
  );
  
  // 检查是否为允许的API路径
  const isAllowedApi = allowedApiPaths.some(path => 
    req.path === path || req.path.startsWith(path)
  );
  
  // 如果是允许的路径，继续处理
  if (isAllowedStatic || isAllowedApi) {
    return next();
  }
  
  // 禁止访问的路径
  console.log(`🚫 拒绝访问: ${req.method} ${req.path} - IP: ${req.ip}`);
  return res.status(403).json({
    code: 403,
    message: '访问被拒绝',
    timestamp: Date.now()
  });
};

// 应用安全中间件
app.use(securityMiddleware);

// 静态文件服务 - 只服务前端公开文件
app.use(express.static(path.join(__dirname, 'public')));

// 公开API代理 - 只代理必要的公开API
app.use('/api/regions', createProxyMiddleware({
  target: 'http://localhost:3001',
  changeOrigin: true,
  logLevel: 'info',
  onProxyReq: (proxyReq, req, res) => {
    console.log('✅ 允许API请求:', req.method, req.url);
  }
}));

app.use('/api/clue-categories', createProxyMiddleware({
  target: 'http://localhost:3001',
  changeOrigin: true,
  logLevel: 'info',
  onProxyReq: (proxyReq, req, res) => {
    console.log('✅ 允许API请求:', req.method, req.url);
  }
}));

app.use('/api/clues', createProxyMiddleware({
  target: 'http://localhost:3001',
  changeOrigin: true,
  logLevel: 'info',
  onProxyReq: (proxyReq, req, res) => {
    console.log('✅ 允许API请求:', req.method, req.url);
  }
}));

app.use('/api/submit-clue', createProxyMiddleware({
  target: 'http://localhost:3001',
  changeOrigin: true,
  logLevel: 'info',
  onProxyReq: (proxyReq, req, res) => {
    console.log('✅ 允许API请求:', req.method, req.url);
  }
}));

app.use('/api/send-sms', createProxyMiddleware({
  target: 'http://localhost:3001',
  changeOrigin: true,
  logLevel: 'info',
  onProxyReq: (proxyReq, req, res) => {
    console.log('✅ 允许API请求:', req.method, req.url);
  }
}));

app.use('/api/verify-sms', createProxyMiddleware({
  target: 'http://localhost:3001',
  changeOrigin: true,
  logLevel: 'info',
  onProxyReq: (proxyReq, req, res) => {
    console.log('✅ 允许API请求:', req.method, req.url);
  }
}));

// 处理根路径和允许的HTML页面
app.get('/', (req, res) => {
  console.log('✅ 访问首页:', req.ip);
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.get('/index.html', (req, res) => {
  console.log('✅ 访问首页:', req.ip);
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.get('/submit.html', (req, res) => {
  console.log('✅ 访问提交页面:', req.ip);
  res.sendFile(path.join(__dirname, 'public', 'submit.html'));
});

// 所有其他请求都返回403
app.use('*', (req, res) => {
  console.log(`🚫 拒绝访问: ${req.method} ${req.path} - IP: ${req.ip}`);
  res.status(403).json({
    code: 403,
    message: '访问被拒绝 - 仅允许访问主页和线索提交页面',
    timestamp: Date.now()
  });
});

app.listen(PORT, () => {
  console.log(`🚀 安全代理服务器启动成功！`);
  console.log(`📡 前端服务: http://localhost:${PORT}`);
  console.log(`✅ 允许访问: 主页(/) 和 线索提交(/submit.html)`);
  console.log(`🚫 禁止访问: 管理后台(/admin) 和其他敏感页面`);
  console.log(`🔒 安全模式: 已启用访问控制`);
  console.log(`📝 请确保后端API服务器在3001端口运行`);
});

// 错误处理
process.on('uncaughtException', (err) => {
  console.error('未捕获的异常:', err);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('未处理的Promise拒绝:', reason);
}); 